import { useEffect, useState } from 'react';
import {
  Button,
  Space,
  Form,
  Row,
  Col,
  Input,
  Table,
  Popconfirm,
  Popover,
  Modal,
  InputNumber,
  List,
  Cascader,
} from 'antd';
import usePageAccess from '@/components/usePageAccess';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import { QueryCityVipListParams, MoneyCardTemplate, delCityVip, CityVip } from './services';
import {
  queryCityVip, delMoneyCardTemplate, makeCardBatch, getStationsById,
} from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import Ellipsis from '@/components/Ellipsis';
import dayjs from 'dayjs';
import CardListModal, { CardListModalProps } from './components/CardListModal';
import { EyeOutlined } from '@ant-design/icons';
import { jump2target } from '@/utils/common';
import {  queryCityOptions2WithOutD } from '@/services/common';

const MoneyCardTemplatePage: React.FC = () => {
  const access = usePageAccess()
  const [makeCardForm] = Form.useForm()
  const [searchForm] = Form.useForm<QueryCityVipListParams>()
  const [cityName, setCityName] = useState<string>()
  const [cityId, setCityId] = useState<string>()
  const cityOptions = useRequest(queryCityOptions2WithOutD)
  const [searchParams, setSearchParams] = useState<QueryCityVipListParams>({
    pageNum: 1, pageSize: 10,
  })
  const moneyCardList = useRequest(() => queryCityVip(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: delMoneyCardTemplateAsync } = useRequest(delCityVip, {manual: true})
  const { runAsync: makeCardBatchAsync, loading: makeCardBatchLoading } = useRequest(makeCardBatch, {manual: true})
  const { runAsync: getStations } = useRequest(getStationsById, {manual: true})
  const [makeCardRecord, setMakeCardRecord] = useState<MoneyCardTemplate>()
  const [cardListModalProps, setCardListModalProps] = useState<CardListModalProps>()

  const editTemplate = (record: any) => {
    sessionStorage.setItem('logisticsNNTemplateData', JSON.stringify(record))
    sessionStorage.setItem('__/coupon/cityVipList/edit_title', '编辑城市会员')
    history.push('/coupon/cityVipList/edit')
  }
  const openEditPage = (title: string) => {
    jump2target(`/coupon/cityVipList/edit`, {needRefresh: true})
    sessionStorage.setItem('__/coupon/cityVipList/edit_title', title)
  }

  const onFinish = (formValues: any) => {
    console.info('甲氨基：', formValues)
    let cityId = null;
    if (formValues.title && formValues.title.length > 0)
    {
      cityId = formValues.title[formValues.title.length - 1];
    }
    setSearchParams({
      ...searchParams,
      ...formValues,
      cityId:cityId,
      pageNum: 1,
    })
  }

  const openMakeCardModal = (record: MoneyCardTemplate) => {
    setMakeCardRecord(record)
  }

  const onMakeCardModalCancel = () => {
    makeCardForm.resetFields()
    setMakeCardRecord(undefined)
  }

  const onCityChange = (value: any, item: any) => {
    console.info('选中城市：', item)
    if (item.length) {
      setCityId(item[item.length - 1].value)
    }
  }

  const onMakeCardModalOk = () => {
    makeCardForm.validateFields()
    .then((values: any) => {
      makeCardBatchAsync({
        id: makeCardRecord!.id,
        num: values.num,
      }).then(() => {
        moneyCardList.refresh()
        onMakeCardModalCancel()
      })
    })
  }

  const openMakeCardListModal = (record: MoneyCardTemplate) => {
    setCardListModalProps({
      infoId: record.id,
    })
  }

  const onCardListModalCancel = () => {
    setCardListModalProps(undefined)
  }

  const showAllStation = (id: MoneyCardTemplate['id']) => {
    getStations({infoId: id, pageSize: 100, pageNum: 1}).then(res => {
      Modal.info({
        title: '适用场站',
        content: <List
          dataSource={res.data}
          renderItem={item => <List.Item>{item.stationName}</List.Item>}
        />
      })
    })
  }

  const columns: ColumnsType<CityVip> = [
    {
      title: '省份城市',
      dataIndex: 'infoType',
      width: 120,
      render: (val, record) => {
        if (record.infoType === 1) {
          return '全国'
        } else if (record.infoType === 2) {
          return record.province
        } else if (record.infoType === 3) {
          return record.province + record.city
        }
      }
    },
    {
      title: '期限',
      dataIndex: 'dayType',
      width: 100,
      render: (val, record) => {
        if (val === 1) {
          return '月'
        } else if (val === 2) {
          return '季'
        } else if (val === 3) {
          return '年'
        }
      }
    },
    {
      title: '金额(元)',
      dataIndex: 'payMoney',
      width: 120,
    },

    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 160,
      render: val => val && dayjs(val).format('YYYY-MM-DD')
    }
    ,
    {
      title: '操作',
      dataIndex: 'id',
      width: 160,
      fixed: 'right',
      render: (id: number, record) => {
        return <Space>
          <a  onClick={() => editTemplate(record)}>编辑</a>
          <Popconfirm
            title={`确定删除吗?`}
            onConfirm={() => delMoneyCardTemplateAsync({id: record.id}).then(moneyCardList.refresh)}
            okText="删除"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      moneyCardList.refresh()
    }
    window.addEventListener('refreshMoney1CardTemplateList', refresh)
    return () => {
      window.removeEventListener('refreshMoney1CardTemplateList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <Access accessible={!!access.add || true}>
          <div className="toolbar">
            <Space>
              <Button type='primary' onClick={() => openEditPage('添加城市会员')}>添加城市会员</Button>
            </Space>
          </div>
        </Access>
        <div className="form-area">
          <Form name='searchMoneyCardForm' form={searchForm} onFinish={onFinish}>
            <Row>
              <Col span={10}>
                <Form.Item label='省份城市' name='title'>
                  <Cascader
                    loading={cityOptions.loading}
                    options={cityOptions.data?.data}
                    style={{width: 320}}
                    placeholder='请选择'
                    changeOnSelect
                    onChange={onCityChange}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={moneyCardList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<MoneyCardTemplate>
          rowKey='id'
          loading={moneyCardList.loading}
          dataSource={moneyCardList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: moneyCardList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <Modal
        open={!!makeCardRecord}
        title='批量制卡'
        width={400}
        onCancel={onMakeCardModalCancel}
        onOk={onMakeCardModalOk}
        confirmLoading={makeCardBatchLoading}
      >
        <Form form={makeCardForm} name='makeCardForm' labelCol={{span: 6}}>
          <Form.Item label='卡模板'>{makeCardRecord?.title}</Form.Item>
          <Form.Item label='数量' name='num' rules={[{required: true, message: '请输入制卡数量'}]}>
            <InputNumber placeholder='请输入' style={{width: '100%'}} min={1} max={100} precision={0} />
          </Form.Item>
        </Form>
      </Modal>
      <CardListModal
        {...cardListModalProps}
        onCancel={onCardListModalCancel}
      />
    </div>
  );
};

export default MoneyCardTemplatePage;
